﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Ev.Answer
{
    public partial class Setting : Form
    {
        
        XmlConfigUtil util = new XmlConfigUtil(StaticData.xmlUrlPath);

        //初始化xml
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement xmlRoot;



        /// <summary>
        /// 分类数据源集合
        /// </summary>
        List<ModelKeyValue> listType = new List<ModelKeyValue>();
        List<ModelKeyValue> listTitle = new List<ModelKeyValue>();
        public Setting()
        {
            InitializeComponent();
        }

        private void Setting_Load(object sender, EventArgs e)
        {
            lbType.ItemHeight = 17;
            ReLoadData();
        }


        #region 保存添加节点

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtTitle.Text) || string.IsNullOrEmpty(this.txtType.Text))
            {
                MessageBox.Show("请输入题目信息");
                return;
            }

            var strNodeType = string.Empty;
            var strNodeTitle = string.Empty;

            //判断分类是否已存在
            var nodeTypeList = xmlRoot.SelectNodes(StaticData.TypeNode + "[@Name='" + txtType.Text + "']");

            XmlElement nodeType;
            if (nodeTypeList == null || nodeTypeList.Count == 0)
            {
                nodeType = SaveXmlTypeTitle(StaticData.TypeNode, txtType.Text, xmlRoot, StaticData.TypeIndex);
            }
            else
            {
                nodeType = (XmlElement)nodeTypeList.Item(0);
            }

            //判断问题是否已存在
            XmlElement nideTitle;
            var nodeTitleList = nodeType.SelectNodes(StaticData.QuestionNode + "[@Name='" + txtTitle.Text + "']");
            if (nodeTitleList == null || nodeTitleList.Count == 0)
            {
                nideTitle = SaveXmlTypeTitle(StaticData.QuestionNode, txtTitle.Text, nodeType, StaticData.TitleIndex);
            }
            else
            {
                nideTitle = (XmlElement)nodeTitleList.Item(0);
            }
            nideTitle.InnerXml = "";
            //添加问题答案
            initABCD(nideTitle, txtA.Text, "A", cbA.Checked);
            initABCD(nideTitle, txtB.Text, "B", cbB.Checked);
            initABCD(nideTitle, txtC.Text, "C", cbC.Checked);
            initABCD(nideTitle, txtD.Text, "D", cbD.Checked);
            initABCD(nideTitle, txtE.Text, "E", cbE.Checked);
            initABCD(nideTitle, txtF.Text, "F", cbF.Checked);

            xmlDoc.Save(StaticData.xmlUrlPath);

            ReLoadData();
        }

        void initABCD(XmlElement xmlElem, string strText, string cNo, bool isOK)
        {
            var nodeAnswer = xmlDoc.CreateElement(StaticData.AnswerNode);
            nodeAnswer.SetAttribute("cNo", cNo);
            nodeAnswer.SetAttribute("isOK", isOK.ToString());
            nodeAnswer.InnerText = strText;
            xmlElem.AppendChild(nodeAnswer);
        }

        XmlElement SaveXmlTypeTitle(string strNode, string nodeText, XmlElement nodeElement, string tsIndexName)
        {
            ///添加问题
            var titleIndex = Convert.ToInt32(util.Read("Setting", tsIndexName)) + 1;
            var nodeTitle = xmlDoc.CreateElement(strNode);
            nodeTitle.SetAttribute("sIndex", titleIndex.ToString());
            nodeTitle.SetAttribute("Name", nodeText);
            nodeElement.AppendChild(nodeTitle);

            //修改索引
            var nodeTitleIndex = (XmlElement)xmlRoot.SelectSingleNode("Setting/" + tsIndexName);
            nodeTitleIndex.InnerText = (titleIndex++).ToString();
            return nodeTitle;
        }



        #endregion

        #region 绑定分类和问题数据

        private void ReLoadData()
        {

            if (File.Exists(StaticData.xmlUrlPath))
                xmlDoc.Load(StaticData.xmlUrlPath);
            else
                xmlDoc.LoadXml("<XmlConfig />");
            xmlRoot = (XmlElement)xmlDoc.ChildNodes[1];

            var xmlItemsType = xmlRoot.SelectNodes(StaticData.TypeNode);
            if (xmlItemsType != null)
            {
                listType = new List<ModelKeyValue>();
                foreach (XmlNode item in xmlItemsType)
                {
                    ModelKeyValue model = new ModelKeyValue();
                    model.pid = Convert.ToInt32(item.Attributes["sIndex"].Value);
                    model.strTitle = item.Attributes["Name"].Value;
                    listType.Add(model);
                }

                lbType.DataSource = listType;
                lbType.DisplayMember = "strTitle";
            }
        }

        #endregion


        /// <summary>
        /// 分类选择索引变更时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            var lb = (ListBox)sender;
            var model = listType[lb.SelectedIndex];
            //根据分类索引，查询问题列表
            var nodeTypeInfo = xmlRoot.SelectSingleNode(StaticData.TypeNode + "[@sIndex='" + model.pid + "']");
            if (nodeTypeInfo == null)
            {
                return;
            }
            var nodeTitleList = nodeTypeInfo.SelectNodes(StaticData.QuestionNode);

            listTitle = new List<ModelKeyValue>();
            foreach (XmlNode item in nodeTitleList)
            {
                ModelKeyValue mm = new ModelKeyValue();
                mm.pid = Convert.ToInt32(item.Attributes["sIndex"].Value);
                mm.strTitle = item.Attributes["Name"].Value;
                listTitle.Add(mm);
            }

            lbTitle.DataSource = listTitle;
            lbTitle.DisplayMember = "strTitle";


        }

        /// <summary>
        /// 根据问题查询答案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbTitle_SelectedIndexChanged(object sender, EventArgs e)
        {
            clearForm();

            var lb = (ListBox)sender;
            var model = listType[this.lbType.SelectedIndex];
            //根据分类索引，查询问题列表
            var nodeTypeinfo = xmlRoot.SelectSingleNode(StaticData.TypeNode + "[@sIndex='" + model.pid + "']");
            if (nodeTypeinfo == null) return;
            txtType.Text = nodeTypeinfo.Attributes["Name"].Value;
            var modelTitle = this.listTitle[lb.SelectedIndex];
            if (modelTitle == null) return;
            XmlElement nodeTitleInfo = (XmlElement)nodeTypeinfo.SelectSingleNode(StaticData.QuestionNode + "[@sIndex='" + modelTitle.pid + "']");
            if (nodeTitleInfo == null)
            {
                return;
            }
            txtTitle.Text = nodeTitleInfo.Attributes["Name"].Value;

            var nodeAnswerA = nodeTitleInfo.SelectSingleNode(StaticData.AnswerNode + "[@cNo='A']");
            var nodeAnswerB = nodeTitleInfo.SelectSingleNode(StaticData.AnswerNode + "[@cNo='B']");
            var nodeAnswerC = nodeTitleInfo.SelectSingleNode(StaticData.AnswerNode + "[@cNo='C']");
            var nodeAnswerD = nodeTitleInfo.SelectSingleNode(StaticData.AnswerNode + "[@cNo='D']");
            var nodeAnswerE = nodeTitleInfo.SelectSingleNode(StaticData.AnswerNode + "[@cNo='E']");
            var nodeAnswerF = nodeTitleInfo.SelectSingleNode(StaticData.AnswerNode + "[@cNo='F']");


            if (nodeAnswerA != null)
            {
                cbA.Checked = Convert.ToBoolean(nodeAnswerA.Attributes["isOK"].Value);
                txtA.Text = nodeAnswerA.InnerText;
            }
            if (nodeAnswerB != null)
            {
                cbB.Checked = Convert.ToBoolean(nodeAnswerB.Attributes["isOK"].Value);
                txtB.Text = nodeAnswerB.InnerText;
            }
            if (nodeAnswerC != null)
            {
                cbC.Checked = Convert.ToBoolean(nodeAnswerC.Attributes["isOK"].Value);
                txtC.Text = nodeAnswerC.InnerText;
            }
            if (nodeAnswerD != null)
            {
                cbD.Checked = Convert.ToBoolean(nodeAnswerD.Attributes["isOK"].Value);
                txtD.Text = nodeAnswerD.InnerText;
            }
            if (nodeAnswerE != null)
            {
                cbE.Checked = Convert.ToBoolean(nodeAnswerE.Attributes["isOK"].Value);
                txtE.Text = nodeAnswerE.InnerText;
            }
            if (nodeAnswerF != null)
            {
                cbF.Checked = Convert.ToBoolean(nodeAnswerF.Attributes["isOK"].Value);
                txtF.Text = nodeAnswerF.InnerText;
            }

        }


        void clearForm()
        {
            //txtType.Text = "";
            txtTitle.Text = "";
            txtA.Text = "";
            txtB.Text = "";
            txtC.Text = "";
            txtD.Text = "";
            txtE.Text = "";
            txtF.Text = "";
            cbA.Checked = false; cbB.Checked = false; cbC.Checked = false; cbD.Checked = false; cbE.Checked = false; cbF.Checked = false;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            clearForm();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定要删除问题么？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                //删除
                var listBoxTitle = contextMenuStrip1.SourceControl as ListBox;
                int i = listBoxTitle.SelectedIndex;

                var modelType = listType[lbType.SelectedIndex];
                //listBoxTitle.Items.Remove(listBoxTitle.Items[i]);


                var node = xmlRoot.SelectSingleNode("TypeNode/QuestionNode[@sIndex='" + listTitle[i].pid + "']");

                xmlRoot.SelectSingleNode(StaticData.TypeNode + "[@sIndex='" + modelType.pid + "']").RemoveChild(node);

                xmlDoc.Save(StaticData.xmlUrlPath);
                ReLoadData();
            }
        }
    }
}
